/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 13, 2012  11:03:48 AM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.ps.outbound
 * File Name : SyncBudgetActivityService.java
 * TODO
 */
package sap.business.ps.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.PsProjPlanBudget;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.PsProjPlanBudgetServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class SyncBudgetActivityService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(SyncBudgetActivityService.class);
	private static PsProjPlanBudgetServices psProjPlanBudgetServ= null; 

	/**
	 * 
	 */
	public SyncBudgetActivityService() {
		// TODO Auto-generated constructor stub
		try {
			sap_bapi = "ZIN_PSMAS_BUDGET";
			sap_table = "BUDG_DATA";
			sap_table_return = "RETURN";
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		
		//Check Is not isEmpty is exit method.
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			//log.info("value_list.size : " + value_list.size());			
			//log.info("table.getNumRows : " + jcoTable.getNumRows());
			//log.info("table.getNumColumns : " + jcoTable.getNumColumns());
			
			for (Object obj : value_list) 
	        {
				PsProjPlanBudget model = (PsProjPlanBudget)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				
				jcoTable.setValue("POST1", model.getUnitNumber());
				jcoTable.setValue("POSID", model.getBuildingPhase());
				jcoTable.setValue("ACTGRP", model.getActivityGroupCode());
				jcoTable.setValue("WERKS", model.getSapPlantCode());
				jcoTable.setValue("WTGES", model.getTotalBudget());
				jcoTable.setValue("TWAER", model.getCurrency());
	        }
		}
				
		super.SynchroToSap(jcoFunction, jcoTable, value_list);
	}
	
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		
		List<PsProjPlanBudget> lst = new ArrayList<PsProjPlanBudget>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				PsProjPlanBudget model = psProjPlanBudgetServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			psProjPlanBudgetServ.Updated(lst);
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<PsProjPlanBudget> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<PsProjPlanBudget> newlst = new ArrayList<PsProjPlanBudget>();
				for(PsProjPlanBudget model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new PsProjPlanBudgetServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void SendingToSAP(List<PsProjPlanBudget> value_list) throws Exception {
		try{
			if(!CommonService.IsNull(value_list))
			{
				this.jco_conn  = new Connection();

				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Send to SAP
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				psProjPlanBudgetServ = new PsProjPlanBudgetServices(this.emSynchro);
				//List<PsProjPlanBudget> value_list = psProjPlanBudgetServ.findAllIsSync("N");		
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);	
			}
		}catch(Exception e){
			
			UpdateStagingWhenError(value_list, e);

			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	private void Start() throws Exception
	{
		this.sap_bapi = "ZIN_PSMAS_BUDGET";
		this.sap_table = "BUDG_DATA";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();

		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		psProjPlanBudgetServ = new PsProjPlanBudgetServices(this.emSynchro);
		List<PsProjPlanBudget> value_list = psProjPlanBudgetServ.findAllIsSync("N");		
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);		
	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		
//		try{
//			new SyncBudgetActivityService().Start();
//			
//		}catch(Exception e)
//		{
//			log.error(e);
//		}
//
//	}

}
